﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XiDainChangAn.OA.IBLL;
using XiDainChangAn.OA.WebApp.Models;
using XiDainChangAn.OA.WF;
using XiDianChangAn.OA.Model;

namespace XiDainChangAn.OA.WebApp.Controllers
{
    [MyLoginCheckFilterAttribute(IsCheck = false)]
    public class WFInstanceController : Controller
    {
        public IWF_TempService WF_TempService { get; set; }
        public IUserInfoService UserInfoService { get; set; }
        public IWF_InstanceService WF_InstanceService { get; set; }
        public IWF_StepService WF_StepService { get; set; }

        #region 01，发起流程实例+ActionResult Add(int id)
        /// <summary>
        /// 发起流程实例
        /// </summary>
        /// <param name="id">流程实例id</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Add(int id)
        {
            var instance= WF_InstanceService.GetById(id);
            var temp = WF_TempService.GetEntitys(u => u.Id ==instance.WF_TempId ).FirstOrDefault();
            ViewBag.Id = temp.Id;
            ViewBag.Name = temp.TemName;
            ViewBag.Desc = temp.Desc;
            WF_Instance model = new WF_Instance();
            model.Content = temp.TempForm;

            var user = UserInfoService.GetEntitys(u => u.DelFlag == (short)XiDianChangAn.OA.Model.Enum.DelFlagEnum.Normal).ToList();
            ViewData["UserList"] = (from u in user select new SelectListItem() { Selected = false, Text = u.ShowName, Value = u.Id + "" }).ToList();
            return View(model);
        } 
        #endregion

        #region 01,发起流程实例+ActionResult Add(WF_Instance instance, int Id, int UserList)
        /// <summary>
        /// 发起流程实例
        /// </summary>
        /// <param name="moder"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(WF_Instance instance, int Id, int UserList)
        {
            var currentUserId = 1;

            //在工作流程实例表添加一条数据
            instance.DelFlag = (short)XiDianChangAn.OA.Model.Enum.DelFlagEnum.Normal;
            instance.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            instance.FilePath = string.Empty;
            instance.StartBy = currentUserId;
            instance.Level = 0;
            instance.Status = (short)XiDianChangAn.OA.Model.Enum.WFStemEnum.Processing;
            instance.WFInstanceId = Guid.Empty;
            instance.WF_TempId = Id;

            WF_InstanceService.Add(instance);

            //第二点：启动工作流
            var wfApp = WorkflowApplicationHelper.CreateWorkflowApp(new FincalActivity(), instance.Id,null);
            instance.WFInstanceId = wfApp.Id;
            WF_InstanceService.UpDate(instance);

            //第三点：在步骤表里面  一个当前已经处理完成的步骤
            WF_Step startStep = new WF_Step();
            startStep.WF_InstanceId = instance.Id;
            startStep.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            startStep.StepName = "提交审批表单";
            startStep.IsEndStep = 0;
            startStep.IsStartStep = 1;
            startStep.ProcessBy = 1;
            startStep.ProcessResult = "通过";
            startStep.ProcessCommon = "提交申请";
            startStep.ProcessTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            startStep.StepStatus = (short)XiDianChangAn.OA.Model.Enum.WFStemEnum.Processed;
            WF_StepService.Add(startStep);

            //WorkflowApplicationHelper.ResumeBookMark(new FincalActivity(), startStep.WF_Instance.WFInstanceId, startStep.StepName, 1);
          
            //第二步骤：下一步该谁审批   项目经理
            WF_Step nextStep = new WF_Step();
            nextStep.WF_InstanceId = instance.Id;
            nextStep.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            nextStep.ProcessTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            nextStep.ProcessCommon = string.Empty;
            nextStep.IsEndStep = 0;
            nextStep.IsStartStep = 0;
            nextStep.ProcessBy = (short)UserList;
            nextStep.ProcessResult = "";
            nextStep.StepName = "";
            nextStep.StepStatus = (short)XiDianChangAn.OA.Model.Enum.WFStemEnum.NoProcessed;
            WF_StepService.Add(nextStep);

            return RedirectToAction("ShowMyCheck");
        }
        #endregion

        #region --,我的流程
        #region 02，我申请审批流程+ActionResult ShowMycheck()
        /// <summary>
        /// 我申请审批流程
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowMycheck()
        {
            var data = WF_InstanceService.GetEntitys(i => i.StartBy == (short)1).ToList();
            return View(data);
        }
        #endregion

        #region 03，我的待审流程+ActionResult ShowMyUnCheck()
        /// <summary>
        /// 我的待审流程
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowMyUnCheck()
        {
            var runEnum = (short)XiDianChangAn.OA.Model.Enum.WFStemEnum.NoProcessed;
            var instanceEnum = (short)XiDianChangAn.OA.Model.Enum.WFStemEnum.Processing;

            //拿到当前用户未处理的步骤
            var step = WF_StepService.GetEntitys(s => s.StepStatus == runEnum && s.ProcessBy == (short)2).ToList();

            //通过我没有处理的步骤拿到流程的实例id
            var instanceIds = (from s in step select s.WF_InstanceId).Distinct();

            //流程实例的id拿到所有的流程实例
            var data = WF_InstanceService.GetEntitys(i => instanceIds.Contains(i.Id) && i.Status == instanceEnum).ToList();



            return View(data);
        }
        #endregion

        #region 04
        /// <summary>
        /// 我的已完成审批流程
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowMyChecked()
        {
            var runEnum = (short)XiDianChangAn.OA.Model.Enum.WFStemEnum.NoProcessed;
            var instanceEnum = (short)XiDianChangAn.OA.Model.Enum.WFStemEnum.Processed;

            //拿到当前用户未处理的步骤
            var step = WF_StepService.GetEntitys(s => s.StepStatus == runEnum && s.ProcessBy == 1).ToList();

            //通过我没有处理的步骤拿到流程的实例id
            var instanceIds = (from s in step select s.WF_InstanceId).Distinct();

            //流程实例的id拿到所有的流程实例
            var data = WF_InstanceService.GetEntitys(i => instanceIds.Contains(i.Id) && i.Status == instanceEnum).ToList();
            return View(data);
        }
        #endregion
        #endregion

        #region 二，审批
        public ActionResult ShowCheck(int id)
        {
            var instance = WF_InstanceService.GetEntitys(u => u.Id == id).FirstOrDefault();

            var user = UserInfoService.GetEntitys(u => u.DelFlag == (short)XiDianChangAn.OA.Model.Enum.DelFlagEnum.Normal).ToList();
            ViewData["stepId"] = WF_StepService.GetEntitys(a => a.WF_InstanceId == instance.Id).Max(a=>a.Id);
            ViewData["userList"] = (from u in user select new SelectListItem() { Selected = false, Text = u.ShowName, Value = u.Id + "" }).ToList();
            return View(instance);
        } 

        /// <summary>
        /// 审批
        /// </summary>
        /// <param name="stepId">当前步骤id</param>
        /// <param name="isPass">是否通过</param>
        /// <param name="Comment">审批意见</param>
        /// <param name="UserList">流转到</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DoCheck(int stepId, string
            isPass, string comment, int userList)
        {
            //更新当前步骤
            var step = WF_StepService.GetEntitys(u => u.Id == stepId).FirstOrDefault();
            step.ProcessResult = isPass;
            step.ProcessTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            step.ProcessCommon = comment;
            WF_StepService.UpDate(step);

            //初始化下一个步骤
            WF_Step next = new WF_Step();
            next.IsEndStep = 0;
            next.IsStartStep = 0;
            next.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            next.ProcessBy = (short)userList;
            next.ProcessResult = string.Empty;
            next.StepStatus = step.StepStatus = (short)XiDianChangAn.OA.Model.Enum.WFStemEnum.NoProcessed;
            next.StepName = string.Empty;
            next.WF_InstanceId = step.WF_InstanceId;
            next.ProcessTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            next.ProcessCommon = string.Empty;

            WF_StepService.Add(next);
            //让书签继续往下执行
            var Value = isPass=="通过" ? 1 : 0;
            WorkflowApplicationHelper.ResumeBookMark(new FincalActivity(), step.WF_Instance.WFInstanceId, step.StepName, Value);
            return Content("OK");
        } 
        #endregion
    }
}